package com.travel.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.travel.mapper.ScenicSpotMapper;
import com.travel.pojo.dto.PageDTO;
import com.travel.pojo.dto.ScenicSpotDTO;
import com.travel.pojo.dto.ScenicSpotQueryDTO;
import com.travel.pojo.entity.ScenicSpot;
import com.travel.pojo.vo.ScenicSpotVO;
import com.travel.service.IScenicSpotService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ScenicSpotServiceImpl extends ServiceImpl<ScenicSpotMapper, ScenicSpot> implements IScenicSpotService {

    @Override
    public PageDTO<ScenicSpotVO> pageListScenicSpot(ScenicSpotQueryDTO scenicSpotQueryDTO) {
        // 设置默认分页值（确保不为null）
        Integer page = scenicSpotQueryDTO.getPage() != null ? scenicSpotQueryDTO.getPage() : 1;
        Integer pageSize = scenicSpotQueryDTO.getPageSize() != null ? scenicSpotQueryDTO.getPageSize() : 10;

        Page<ScenicSpot> pageInfo = Page.of(page, pageSize);

        // 动态查询条件
        Page<ScenicSpot> result = lambdaQuery()
                .like(StringUtils.isNotBlank(scenicSpotQueryDTO.getName()), ScenicSpot::getName, scenicSpotQueryDTO.getName())
                .like(StringUtils.isNotBlank(scenicSpotQueryDTO.getLocation()), ScenicSpot::getLocation, scenicSpotQueryDTO.getLocation())
                .ge(scenicSpotQueryDTO.getMinPrice() != null, ScenicSpot::getTicketPrice, scenicSpotQueryDTO.getMinPrice())
                .le(scenicSpotQueryDTO.getMaxPrice() != null, ScenicSpot::getTicketPrice, scenicSpotQueryDTO.getMaxPrice())
                .page(pageInfo);

        // 转换为VO
        List<ScenicSpotVO> voList = result.getRecords().stream()
                .map(spot -> BeanUtil.copyProperties(spot, ScenicSpotVO.class))
                .collect(Collectors.toList());

        return PageDTO.<ScenicSpotVO>builder()
                .list(voList)
                .total((int) result.getTotal())
                .pages((int) result.getPages())
                .build();
    }

    @Override
    public void createScenicSpots(ScenicSpotDTO scenicSpotDTO) {
        ScenicSpot scenicSpot = BeanUtil.copyProperties(scenicSpotDTO, ScenicSpot.class);

        save(scenicSpot);  // 直接使用 ServiceImpl 的 save 方法
    }

    @Override
    public void updateScenicSpot(Long id, ScenicSpotDTO scenicSpotDTO) {
        ScenicSpot scenicSpot = BeanUtil.copyProperties(scenicSpotDTO, ScenicSpot.class);
        scenicSpot.setId(id);
        updateById(scenicSpot);  // 使用 updateById 更简洁（根据 ID 更新）
    }
}
